package com.demo.paypalmanagement.controller.admin;


import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.demo.paypalmanagement.common.BuildQuery;
import com.demo.paypalmanagement.config.response.BizException;
import com.demo.paypalmanagement.model.entity.Users;
import com.demo.paypalmanagement.model.vo.Result;
import com.demo.paypalmanagement.model.vo.UserVO;
import com.demo.paypalmanagement.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UsersController {

  @Autowired
  private IUsersService usersService;

  @GetMapping
  public ResponseEntity<IPage<Users>> getUsersByPage(
          @RequestParam(defaultValue = "1", name = "currentPage") int pageNum,
          @RequestParam(defaultValue = "10", name = "pageSize") int pageSize,
          @RequestParam(defaultValue = "", name = "queryString") String queryString
  ) {
    IPage<Users> userPage = usersService.getUsersByPage(pageNum, pageSize, queryString);
    return ResponseEntity.ok(userPage);
  }


  @PutMapping("/{id}")
  public ResponseEntity<Users> updateUserExpirationDate(@PathVariable Long id, @RequestBody Users updatedUser) {
    Users users = new Users();
    usersService.updateById(users);
    return ResponseEntity.ok(users);
  }

  @PutMapping("/{id}/reset")
  public ResponseEntity resetPwd(@PathVariable Long id) {
    LambdaUpdateWrapper<Users> wrapper = new LambdaUpdateWrapper<>();
    wrapper.eq(Users::getId, id);
    wrapper.set(Users::getPassword, new BCryptPasswordEncoder().encode("123456"));
    usersService.update(null,wrapper);
    return ResponseEntity.ok("successfully");
  }

  @DeleteMapping("/{id}")
  public ResponseEntity<String> deleteUser(@PathVariable Long id) {
    if(id==1){
        return ResponseEntity.ok("超级管理员不能删除");
    }
    boolean deleted = usersService.removeById(id);
    if (!deleted) {
      return ResponseEntity.notFound().build();
    }
    return ResponseEntity.ok("User deleted successfully");
  }

  @GetMapping("/list")
  public Result list(UserVO vo) {

    return Result.success(usersService.list(BuildQuery.buildUserQuery(vo)));

  }

}

